package com.esd.crm.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.esd.crm.entity.Filegags;
import com.esd.crm.mapper.FilegagsMapper;
import com.esd.crm.service.FilegagsService;
import com.esd.crm.util.FileUtils;
import com.esd.crm.util.KitService;
import com.esd.vo.ReturnResult;

@Service
public class FilegagsServiceImpl implements FilegagsService{
	private static Logger logger = Logger.getLogger(FilegagsServiceImpl.class);
	@Value(value = "${resourceFilePath}")
	private String resourceFilePath; // 超级管理员执行初始化文件时 存放的路径-资源文件保存路径
	@Value(value = "${tempFilePath}")
	private String tempFilePath; // 刚上传文件的缓存目录
	@Value(value = "${fileNameSpliter}")
	private String fileNameSpliter;// 新旧文件名分隔符

	@Autowired
	private FilegagsMapper filegagsMapper ;

	@Override
	public boolean insertSelective(Filegags filegags) {
		boolean flag = false;
		if (filegags == null) {
			logger.info("object is null");
			return false;
		}
		if (StringUtils.isBlank(filegags.getId())) {
			filegags.setId(KitService.getUUID());
		}
		Date now = new Date();
		if (filegags.getCreateTime() == null) {
			filegags.setCreateTime(now);
		}
		if (filegags.getUpdateTime() == null) {
			filegags.setUpdateTime(now);
		}
		flag = filegagsMapper.insertSelective(filegags);
		System.out.println("flag====>"+flag);
		return flag;
	}

	//@Override
	private Filegags moveFileToResourcePathAndSaveFileToDB(String srcFolderPath, String destFolderPath,
			Filegags filegags, String operatorId) {
			String fileName = filegags.getFileName();
			if (StringUtils.isBlank(fileName)) {
				logger.warn(
						"moveFileToResourcePathAndSaveFileToDB(String fileName), fileName is null");
				System.out.println(
						"moveFileToResourcePathAndSaveFileToDB(String fileName), fileName is null");
				return null;
			}
			// 通过循环将文件移动到资源文件夹下, 并根据${isSavedToDB}来决定是否放到数据库中
			// 1- 拼装新旧文件名原文件名为 uuid${fileNameSpliter}原文件名.后缀的格式, 将其改变一下
			String suffix = fileName.substring(fileName.lastIndexOf("."));
			// 此处用来区分开 文件名是否为带${fileNameSpliter}格式的, 如果有则从缓存文件中移动到资源文件夹中
			String newFileName = "";
			String id = "";
//			File destFile = null;
			File srcFile = null;
			if(fileName.indexOf(fileNameSpliter)>0){
				id = fileName.substring(0, fileName.indexOf(fileNameSpliter));
				newFileName = id + suffix;// uuid.后缀
				
				// 2- 组装file对象并验证有无
				srcFile = new File(srcFolderPath + fileName);
				if (!srcFile.exists()) {
					logger.warn("srcFile: " + srcFolderPath + File.separator + fileName + " not exists!");
					System.out.println("srcFile: " + srcFolderPath + fileName + " not exists!");
					return null;
				}
//				File destFolder = new File(destFolderPath);
//				if (!destFolder.exists()) {
//					logger.warn("destFolder: " + destFolder + " not exists! make it!");
//					System.out.println("destFolder: " + destFolder + " not exists! make it!");
//					destFolder.mkdirs();
//				}
				// 2-1 移动文件
//				destFile = new File(destFolderPath + File.separator + newFileName);
//				if (srcFile.renameTo(destFile)) {
//					logger.info("************移动文件 srcFile: " + srcFile.getAbsolutePath() + " 成功**************");
//					System.out.println("************移动文件 srcFile: " + srcFile.getAbsolutePath() + " 成功**************");
//				} else {
//					logger.warn("************移动文件 srcFile: " + srcFile.getAbsolutePath() + " 失败**************");
//					System.out.println("************移动文件 srcFile: " + srcFile.getAbsolutePath() + " 失败**************");
//					return null;
//				}
				// 2-2 看看是否真的移动成功了
//				if (!destFile.exists()) {
//					logger.error("************destFile: " + destFile.getAbsolutePath() + "  不存在**************");
//					System.out.println("************destFile: " + destFile.getAbsolutePath() + "  不存在**************");
//					return null;
//				}
			}
//			else{
//				newFileName = fileName;
//				destFile = new File(destFolderPath + File.separator + newFileName);
//				if (!destFile.exists()) {
//					logger.error("************destFile: " + destFile.getAbsolutePath() + "  不存在**************");
//					System.out.println("************destFile: " + destFile.getAbsolutePath() + "  不存在**************");
//					return null;
//				}
//			}
			filegags.setId(id);
			filegags.setFileName(newFileName);
			filegags.setCreateBy(operatorId);
			filegags.setUpdateBy(operatorId);
			Date now = new Date();
			filegags.setCreateTime(now);
			filegags.setUpdateTime(now);
			filegags.setFileSuffix(suffix);
			filegags.setLength(srcFile.length());
			filegags.setFile(FileUtils.getByteFromFile(srcFile));
		return filegags;
	}
	/**
	 * 保存文件
	 */
	@Override
	public ReturnResult addFile(Filegags filegags, HttpServletRequest request, HttpSession session) {
		boolean b = false;
		// 2- 非文件夹时
		if (StringUtils.isBlank(filegags.getFileName())) {
			System.out.println("没有上传任何文件");
			return ReturnResult.fail("没有上传任何文件");
		}
		// 2-1 处理上传的文件列表, 将文件移动到资源文件夹中
//		String tempFolderPath = request.getSession().getServletContext().getRealPath(tempFilePath);
		String tempFolderPath = (String) session.getAttribute("filepath");
		String resourcesFolderPath = request.getSession().getServletContext().getRealPath(resourceFilePath);
		filegags = moveFileToResourcePathAndSaveFileToDB(tempFolderPath,resourcesFolderPath, filegags,  "1");
		if(filegags==null){
			System.out.println("处理上传文件时发生错误.");
			logger.error("处理上传文件时发生错误.");
			return ReturnResult.fail("操作发生错误, 请联系管理员.");
		}
		//System.out.println(filegags.toString());
		b = insertSelective(filegags);
		System.out.println("b====>"+b);
		if(!b) {
			System.out.println("文件上传失败！");
			return ReturnResult.fail("文件上传失败！");
		}
		return ReturnResult.success();
	}

	@Override
	public boolean deleteByPrimaryKey(String id) {
		return filegagsMapper.deleteByPrimaryKey(id);
	}

	@Override
	public boolean deleteBatch(String[] ids) {
		return filegagsMapper.deleteBatch(ids);
	}

	@Override
	public Filegags selectByPrimaryKey(String fileId) {
		return filegagsMapper.selectByPrimaryKey(fileId);
	}

	@Override
	public Filegags moveFileToResourcePathAndSaveFileToDB(String srcFolderPath, String destFolderPath, String fileName,
			String operatorId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean deleteByBusinessId(String id) {
		return filegagsMapper.deleteByBusinessId(id);
	}

	@Override
	public List<Filegags> getFileListByBusinessId(String id) {
		
		return filegagsMapper.getFileListByBusinessId(id);
	} 
	
	

}
